//
//  PlayViewController.m
//  MyListenMusicFun
//
//  Created by dllo on 16/1/18.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AFNetBlock.h"
#import "ViewModel.h"
#import "MusicMp3Model.h"
#import "PlayerManager.h" // 播放器
#import "PlayModel.h"
#import <UIImageView+WebCache.h>
#import "PlayTableViewCell.h"
#import "TopicTableViewCell.h"



@interface PlayViewController () <UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, strong)ViewModel *viewModel;//视图数据
@property(nonatomic, strong)UIView *topView;//上部视图
@property(nonatomic, strong)UITableView *tableView;//tableView
@property(nonatomic, strong)NSMutableArray *soundDataArr;//声音数据
@property (nonatomic, strong) UIImageView *mainView;/**< 旋转的头 */
@property (nonatomic, strong) NSMutableArray *mp3MusicArr;/**< 播放用的数组 */
@property (nonatomic, strong) AppDelegate *appdelegate; /**< 单利对象 */
@property (nonatomic, strong) UISlider *slider;/**< 进度条 */
@end

@implementation PlayViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    NSLog(@"%@", self.urlStr);
    
    //数据请求
    [self dataHandler];
    
    
}

#pragma mark - 播放器方法
- (void)musicPlayer:(NSMutableArray *)dataArr
{
    self.appdelegate = [UIApplication sharedApplication].delegate;
    _appdelegate.playerManager = [PlayerManager defaultManager];
    _appdelegate.playerManager.playerType = PlayTypeList;
    [_appdelegate.playerManager changeMusicWithIndex:0];
    
    if (dataArr.count != 0) {
        _appdelegate.playerManager.musicArray =[NSMutableArray arrayWithArray:dataArr];
        [_appdelegate.playerManager play];
        
    }
    
   // _slider.value = _appdelegate.playerManager.currentTime;
    [self progressObserving];
 
}

#pragma mark - 上一首 下一首
- (void)pushLastMusic:(UIButton *)btn
{
    [_appdelegate.playerManager lastMusic];
}

- (void)pushNextMusic:(UIButton *)btn
{
    [_appdelegate.playerManager nextMusic];
}
#pragma mark - slider走方法
-(void)progressObserving{
    __weak PlayViewController *VC = self;
    [VC.appdelegate.playerManager.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //       VC.bofang.selected  = YES;
        VC.slider.value = VC.appdelegate.playerManager.currentTime / VC.appdelegate.playerManager.totalTime;
        
        if (VC.slider.value == 1) {
            [VC.appdelegate.playerManager playerDidFinish];
        }
        
        
    }];
}

#pragma mark - 数据请求
-(void)dataHandler{
    [AFNetBlock GetDataWithURL:_urlStr block:^(id block) {
        NSDictionary *viewDic = block[@"album"];

        self.viewModel = [ViewModel modelWithDic:viewDic];

        NSArray *array = block[@"tracks"][@"list"];
        self.soundDataArr = [PlayModel modelHanderWithArray:array];
        
        self.mp3MusicArr = [MusicMp3Model modelHanderWithArray:array];
        
        NSMutableArray *playlist = [NSMutableArray array];
        for (MusicMp3Model *m in _mp3MusicArr) {
            NSString *str = m.playUrl64;
            [playlist addObject:str];
        }
        //NSLog(@"%@", playlist);
        
        [self musicPlayer:playlist];
        
        //导航栏
        self.navigationItem.title = _viewModel.title;
        
        //铺设视图
        [self viewSet];
        
        //tableView
        [self tableViewSet];
        [_tableView reloadData];
    }];
}

#pragma mark - 视图铺设
-(void)viewSet{
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 160 * PH)];
    [self.topView NightWithType:UIViewColorTypeNormal];
    //_topView.backgroundColor = [UIColor colorWithRed:50 / 225.0 green:30 / 225.0 blue:39 / 255.0 alpha:1.0];
    [self.view addSubview:_topView];
    
    self.mainView = [[UIImageView alloc] initWithFrame:CGRectMake(20 * PW, 30 * PH, 100 *PW, 100 * PH)];
//    imgView.backgroundColor = [UIColor cyanColor];
    [_topView addSubview:_mainView];
    [_mainView sd_setImageWithURL:[NSURL URLWithString:_viewModel.coverWebLarge] placeholderImage:[UIImage imageNamed:@"musicSmall"]];
    _mainView.layer.cornerRadius = _mainView.frame.size.width / 2;
    _mainView.clipsToBounds = YES;

    
    UIImageView *headImg = [[UIImageView alloc] initWithFrame:CGRectMake(130 * PW, 30 * PH, 30 * PW, 30 *PH)];
    headImg.layer.cornerRadius = 15;
    headImg.clipsToBounds = YES;
    [_topView addSubview:headImg];
    [headImg sd_setImageWithURL:[NSURL URLWithString:_viewModel.avatarPath]];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(170 * PW, 30 * PH, 150 * PW, 30 * PH)];
    [_topView addSubview:nameLabel];
    nameLabel.text = _viewModel.nickname;
    [nameLabel NightWithType:UIViewColorTypeNormal];
//    nameLabel.textColor = [UIColor whiteColor];

    

    // 上一首
    UIButton *lastBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    lastBtn.frame = CGRectMake(130 * PW, 90 * PH, 30 * PW, 30 * PH);
    [lastBtn setImage:[UIImage imageNamed:@"lastMusic"] forState:(UIControlStateNormal)];
    [_topView addSubview:lastBtn];
    [lastBtn addTarget:self action:@selector(pushLastMusic:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 进度条
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(160 * PW, 90 * PH, 150 * PW, 30 * PH)];
    [_topView addSubview:_slider];
    
    // 下一首
    UIButton *nextBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    nextBtn.frame = CGRectMake(310 * PW, 90 * PH, 30 * PW, 30 * PH);
    [_topView addSubview:nextBtn];
    [nextBtn setImage:[UIImage imageNamed:@"nextMusic"] forState:(UIControlStateNormal)];
    [nextBtn addTarget:self action:@selector(pushNextMusic:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 收藏按钮
//    UIButton *shoucang = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    shoucang.frame = CGRectMake(310 * PW, 40 * PH, 30 * PW, 30 * PH);
//    [shoucang setImage:[UIImage imageNamed:@"shoucang1"] forState:(UIControlStateNormal)];
//    [shoucang addTarget:self action:@selector(shoucang) forControlEvents:(UIControlEventTouchUpInside)];
//    [_topView addSubview:shoucang];

//    
//    UILabel *introLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 70, 150, 20)];
//    [_topView addSubview:introLabel];
//    introLabel.text = _viewModel.intro;
//    introLabel.textColor = [UIColor whiteColor];
//    introLabel.font = [UIFont systemFontOfSize:15];
//  
//    
//    UILabel *tagsLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 100, 200, 30)];
//    [_topView addSubview:tagsLabel];
//    tagsLabel.text = _viewModel.tags;
//    tagsLabel.textColor = [UIColor whiteColor];
//    tagsLabel.font = [UIFont systemFontOfSize:15];
 
}

#pragma mark - 收藏
- (void)shoucang
{
    
}

#pragma mark - tableView铺设
-(void)tableViewSet{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 224 * PH, self.view.frame.size.width, self.view.frame.size.height - 224 * PH) style:UITableViewStylePlain];
//    _tableView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[PlayTableViewCell class] forCellReuseIdentifier:@"playCell"];
}

#pragma mark - tableView协议方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _soundDataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PlayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"playCell" forIndexPath:indexPath];
    PlayModel *model = _soundDataArr[indexPath.row];
    cell.titleLabel.text = model.title;
    
    if ([model.playtimes floatValue] > 100000000) {
        NSString *str = [NSString stringWithFormat:@"%.1f亿", [model.playtimes floatValue] / 100000000];
        cell.playtimesLabel.text = str;
    }else if ([model.playtimes floatValue] > 10000){
        NSString *str = [NSString stringWithFormat:@"%.1f万", [model.playtimes floatValue] / 10000];
        cell.playtimesLabel.text = str;
    }else {
        cell.playtimesLabel.text = [NSString stringWithFormat:@"%@", model.playtimes];
    }
    
    NSString *str = [NSString stringWithFormat:@"%02ld:%.02ld", [model.duration integerValue] / 60, [model.duration integerValue] % 60];
    cell.durationLabel.text = str;
    
    cell.commentsLabel.text = [model.comments stringValue];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PlayModel *model = _soundDataArr[indexPath.row];
    CGFloat h = [TopicTableViewCell heightWithText:model.title width:WIDTH - 20];
    return 40 + h;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    // 旋转方法
    //self.mainView.transform = CGAffineTransformRotate(self.mainView.transform, M_1_PI - 0.3);
    
    [_appdelegate.playerManager changeMusicWithIndex:indexPath.row];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
